package com.kajespero.webapp.editor.annotation.process;

import java.beans.PropertyEditor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.PropertyEditorRegistry;

import com.kajespero.webapp.editor.annotation.PropertyEditorSupport;
import com.kajespero.webapp.editor.commons.IPropertyEditorSupport;

public class PropertyEditorSupportAnnotationProcess {
	
	private static final Log LOG = LogFactory.getLog(PropertyEditorSupportAnnotationProcess.class);
	
	public static <T> void register(PropertyEditorRegistry registry, T instance ){
		Field [] fields = instance.getClass().getDeclaredFields();
		for(Field field : fields){
			PropertyEditorSupport propertyEditorSupport = field.getAnnotation(PropertyEditorSupport.class);
			if(propertyEditorSupport != null){
				register(registry, propertyEditorSupport);
			}
		}
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private static void register(PropertyEditorRegistry registry, PropertyEditorSupport propertyEditorSupport){
		Class<IPropertyEditorSupport> clazzEditor = (Class<IPropertyEditorSupport>) propertyEditorSupport.editor();
		try {
			IPropertyEditorSupport<?, ?> editor = clazzEditor.newInstance();
			String fieldName = propertyEditorSupport.fieldName();
			Class<?> clazz = editor.getBeanClass();
			registry.registerCustomEditor(clazz, fieldName, (PropertyEditor) editor);
			
		} catch (InstantiationException e) {
			LOG.error("InstantiationException " + e.getMessage(), e);
		} catch (IllegalAccessException e) {
			LOG.error("IllegalAccessException " + e.getMessage(), e);
		}
	}

	public static <T> List<PropertyEditorSupport> getPropertyEditorSupportAnnotations(T instance){
		List<PropertyEditorSupport> annotations = new ArrayList<PropertyEditorSupport>();
		Field [] fields = instance.getClass().getDeclaredFields();	
		for(Field field : fields){
			PropertyEditorSupport propertyEditorSupport = field.getAnnotation(PropertyEditorSupport.class);
			if(propertyEditorSupport != null){
				annotations.add(propertyEditorSupport);
			}
		}
		return annotations;
	}
}
